package cc.yugu.yhdw.common.tool.netty;

import io.netty.buffer.ByteBuf;

public abstract class Message extends TypeOperator {
    public static final byte MSG_FLAG = (byte) 2;
    public static final byte FLAG_1 = (byte) '*';
    private int feature;
    private long serial;
    private long time;
    private short version;

    public abstract int getMsgCode();
    public void readData(ByteBuf buffer) {
    }
    public void writeData(ByteBuf buffer) {
    }

    public final void decode(ByteBuf buffer) {

        buffer.readByte();
        buffer.readByte();
        feature = buffer.readInt();

        int msgCode = buffer.readInt();
        assert msgCode == getMsgCode();

        serial = buffer.readLong();
        time = buffer.readLong();

        version = buffer.readShort(); //读取版本

        buffer.readInt(); //包体长度
        readData(buffer);
    }
    public final void encode(ByteBuf buffer) {

        if(getMsgCode() == 0) {
            throw new IllegalArgumentException("msgCode is zero");
        }

        int position = buffer.writerIndex();

        buffer.writeByte(MSG_FLAG);
        buffer.writeByte(FLAG_1);
        buffer.writeInt(feature);

        buffer.writeInt(getMsgCode());
        buffer.writeLong(serial);
        buffer.writeLong(time == 0 ? time = System.currentTimeMillis() : time);
        buffer.writeShort(version);
        buffer.writeInt(0);
        writeData(buffer);
        buffer.setInt(position + 28, buffer.writerIndex() - position - 32);
    }

    public long getSerial() {
        return serial;
    }

    public void setSerial(long serial) {
        this.serial = serial;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public short getVersion() {
        return version;
    }

    public void setVersion(short version) {
        this.version = version;
    }
}
